package com.useeinfo.oa.open.dashboard.security;

import com.useeinfo.framework.extend.action.BaseAction;
import com.useeinfo.oa.modules.logger.annotations.LoginLogs;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author: 居泽平  Date: 14-11-5
 */
@Controller
@RequestMapping("/security")
public class LoginAction extends BaseAction {

    @Autowired
    private HttpServletRequest httpServletRequest;
    /**
     * 登录页面
     *
     * @return
     */
    @RequestMapping("/login")
    public ModelAndView login(HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if(auth instanceof AnonymousAuthenticationToken){
            modelAndView.setViewName("security/login");
            return modelAndView;
        }
        try {
            response.sendRedirect("index.action");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    /**
     * 首页
     *
     * @return
     */
    @RequestMapping("/index")
    public ModelAndView index(HttpServletRequest request,HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if(auth instanceof AnonymousAuthenticationToken){
            modelAndView.setViewName("security/login");
            return modelAndView;
        }
        modelAndView.setViewName("pages/index");
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        modelAndView.addObject("user", systemUser == null ? null : systemUser.toLoginJSONObject());
        return modelAndView;
    }

    @RequestMapping("/loginout")
    @LoginLogs(check = true, type = "sign out")
    public ModelAndView loginout() {
        try{
            SessionKeyUtils.setSessionEnterprise(httpServletRequest,null);
            SessionKeyUtils.setSessionUser(httpServletRequest,null);
        }catch (Exception e){
            logger.info("session过期直接退出登陆");
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/logout.action");
        return modelAndView;
    }

}
